export const flatTree = (data, cb) => {
  let res = [];
  data.forEach((v) => {
    res.push(cb(v));
    if (v.children && v.children.length) {
      res = res.concat(flatTree(v.children, cb));
    }
  });
  return res;
};

export const makeTree = (data) => {
  let res = [...data];
  const findIndex = () => {
    const childIndex = res.findIndex((v) =>
      res.every((item) => item.pid !== v.id),
    );
    const parentIndex =
      childIndex !== -1
        ? res.findIndex((v) => v.id === res[childIndex].pid)
        : -1;
    return [childIndex, parentIndex];
  };
  let [childIndex, parentIndex] = findIndex();
  while (childIndex > -1 && parentIndex > -1) {
    res[parentIndex].children = [
      ...(res[parentIndex]?.children ?? []),
      res.splice(childIndex, 1)[0],
    ];
    [childIndex, parentIndex] = findIndex();
  }

  return res;
};
